<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF合并工具</title>
    <!-- 本地引用Tailwind CSS -->
    <script src="../../assets/js/tailwind.min.js"></script>
    <link href="../../assets/css/font-awesome.min.css" rel="stylesheet">
    <!-- 本地引用pdf-lib.min.js，FileSaver.min.js -->
    <script src="../../assets/js/pdf-lib.min.js"></script>
    <script src="../../assets/js/FileSaver.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        neutral: '#6B7280',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .pdf-dropzone {
                @apply border-2 border-dashed border-neutral/30 rounded-xl p-8 text-center transition-all duration-300;
            }
            .pdf-dropzone.active {
                @apply border-primary bg-primary/5;
            }
            .pdf-item {
                @apply flex items-center p-4 bg-white rounded-lg shadow-sm border border-gray-100 mb-3 transition-all duration-200;
            }
            .pdf-item:hover {
                @apply shadow-md;
            }
            .btn {
                @apply px-4 py-2 rounded-lg font-medium transition-all duration-200 flex items-center justify-center gap-2;
            }
            .btn-primary {
                @apply bg-primary text-white hover:bg-primary/90 focus:ring-2 focus:ring-primary/50 focus:outline-none;
            }
            .btn-secondary {
                @apply bg-secondary text-white hover:bg-secondary/90 focus:ring-2 focus:ring-secondary/50 focus:outline-none;
            }
            .btn-danger {
                @apply bg-danger text-white hover:bg-danger/90 focus:ring-2 focus:ring-danger/50 focus:outline-none;
            }
            .btn-neutral {
                @apply bg-gray-100 text-gray-700 hover:bg-gray-200 focus:ring-2 focus:ring-gray-300 focus:outline-none;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen font-sans">
    <div class="max-w-5xl mx-auto px-4 py-8">
        <header class="text-center mb-10">
            <h1 class="text-[clamp(1rem,3vw,2rem)] font-bold text-gray-800 mb-2">
                PDF合并工具 <span class="text-primary">📑</span>
            </h1>
        </header>

        <main class="bg-white rounded-2xl shadow-lg p-6 md:p-8 mb-8">
            <!-- 文件上传区域 -->
            <div class="mb-8">
                <div id="pdfDropzone" class="pdf-dropzone cursor-pointer">
                    <div class="flex flex-col items-center">
                        <div class="text-6xl mb-4 text-primary/70">📤</div>
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">拖放PDF文件到这里</h3>
                        <p class="text-gray-500 mb-4">或者</p>
                        <label id="fileInputLabel" class="btn btn-primary cursor-pointer">
                            <span>选择文件</span>
                            <input type="file" id="fileInput" class="hidden" multiple accept=".pdf">
                        </label>
                    </div>
                </div>
            </div>

            <!-- 文件列表区域 -->
            <div class="mb-8">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-semibold text-gray-800">已上传文件 <span id="fileCount">(0)</span></h2>
                    <button id="clearFilesBtn" class="btn btn-neutral text-sm">
                        <span>清空列表</span>
                        <span>🗑️</span>
                    </button>
                </div>
                
                <div id="pdfList" class="space-y-2">
                    <div class="text-center py-8 text-gray-400">
                        <div class="text-4xl mb-2">📄</div>
                        <p>还没有上传任何PDF文件</p>
                    </div>
                </div>
            </div>

            <!-- 合并按钮 -->
            <div class="flex flex-col sm:flex-row gap-4 justify-center">
                <button id="mergeBtn" class="btn btn-secondary text-lg disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    <span>开始合并</span>
                    <span>🔄</span>
                </button>
                <button id="downloadBtn" class="btn btn-primary text-lg disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    <span>下载PDF</span>
                    <span>📥</span>
                </button>
            </div>
        </main>

        <!-- 进度条 -->
        <div id="progressContainer" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
                <h3 class="text-xl font-semibold text-gray-800 mb-4 text-center">正在处理...</h3>
                <div class="w-full bg-gray-200 rounded-full h-2.5 mb-4">
                    <div id="progressBar" class="bg-primary h-2.5 rounded-full" style="width: 0%"></div>
                </div>
                <p id="progressText" class="text-center text-gray-600">准备中...</p>
            </div>
        </div>

        <!-- 结果模态框 -->
        <div id="resultModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
                <div class="text-center mb-4">
                    <div class="text-5xl text-secondary mb-2">✅</div>
                    <h3 class="text-xl font-semibold text-gray-800">PDF合并成功！</h3>
                    <p class="text-gray-600 mt-2">你的PDF文件已成功合并</p>
                </div>
                <div class="flex justify-center">
                    <button id="closeModalBtn" class="btn btn-primary hidden">
                        <span>关闭</span>
                        <span>✖️</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 全局变量
            let pdfFiles = [];
            let mergedPdfBytes = null;
            let isDownloading = false;
            let isUploading = false;
            let resultModalTimeout = null; // 新增结果模态框定时器
            
            // DOM元素
            const pdfDropzone = document.getElementById('pdfDropzone');
            const fileInput = document.getElementById('fileInput');
            const fileInputLabel = document.getElementById('fileInputLabel');
            const pdfList = document.getElementById('pdfList');
            const fileCount = document.getElementById('fileCount');
            const clearFilesBtn = document.getElementById('clearFilesBtn');
            const mergeBtn = document.getElementById('mergeBtn');
            const downloadBtn = document.getElementById('downloadBtn');
            const progressContainer = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');
            const resultModal = document.getElementById('resultModal');
            const closeModalBtn = document.getElementById('closeModalBtn');
            
            // 拖放事件
            pdfDropzone.addEventListener('dragover', (e) => {
                e.preventDefault();
                pdfDropzone.classList.add('active');
            });
            
            pdfDropzone.addEventListener('dragleave', () => {
                pdfDropzone.classList.remove('active');
            });
            
            pdfDropzone.addEventListener('drop', (e) => {
                e.preventDefault();
                pdfDropzone.classList.remove('active');
                
                if (e.dataTransfer.files.length) {
                    handleFiles(e.dataTransfer.files);
                }
            });
            
            // 点击上传
            fileInputLabel.addEventListener('click', (e) => {
                if (isUploading) {
                    e.preventDefault();
                    return;
                }
                fileInput.value = ''; // 重置input值，避免重复选择相同文件
            });
            
            // 文件选择
            fileInput.addEventListener('change', () => {
                if (isUploading || !fileInput.files.length) return;
                
                isUploading = true;
                fileInputLabel.classList.add('opacity-50', 'cursor-not-allowed');
                
                try {
                    handleFiles(fileInput.files);
                } catch (error) {
                    console.error('处理文件失败:', error);
                    alert('处理文件失败，请重试');
                } finally {
                    isUploading = false;
                    fileInputLabel.classList.remove('opacity-50', 'cursor-not-allowed');
                }
            });
            
            // 清空文件
            clearFilesBtn.addEventListener('click', () => {
                pdfFiles = [];
                updateFileList();
            });
            
            // 合并文件
            mergeBtn.addEventListener('click', async () => {
                if (pdfFiles.length < 2) {
                    alert('请至少上传两个PDF文件');
                    return;
                }
                
                showProgress();
                await mergePdfs();
                hideProgress();
                showResultModal();
                
                // 自动关闭结果模态框
                if (resultModalTimeout) clearTimeout(resultModalTimeout);
                resultModalTimeout = setTimeout(hideResultModal, 1000);
            });
            
            // 下载文件
            downloadBtn.addEventListener('click', () => {
                // 防止重复下载
                if (isDownloading || !mergedPdfBytes) return;
                
                isDownloading = true;
                downloadBtn.disabled = true;
                
                try {
                    const blob = new Blob([mergedPdfBytes], { type: 'application/pdf' });
                    saveAs(blob, 'merged.pdf');
                } catch (error) {
                    console.error('下载PDF失败:', error);
                    alert('下载PDF失败，请重试');
                } finally {
                    // 下载完成后重置状态
                    setTimeout(() => {
                        isDownloading = false;
                        downloadBtn.disabled = false;
                    }, 1000);
                }
            });
            
            // 关闭模态框 - 不再需要用户点击
            closeModalBtn.addEventListener('click', () => {
                hideResultModal();
                if (resultModalTimeout) clearTimeout(resultModalTimeout);
            });
            
            // 处理文件
            function handleFiles(files) {
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    if (file.type === 'application/pdf') {
                        pdfFiles.push(file);
                    } else {
                        alert(`${file.name} 不是PDF文件，请上传PDF文件`);
                    }
                }
                updateFileList();
            }
            
            // 更新文件列表
            function updateFileList() {
                fileCount.textContent = `(${pdfFiles.length})`;
                
                if (pdfFiles.length === 0) {
                    pdfList.innerHTML = `
                        <div class="text-center py-8 text-gray-400">
                            <div class="text-4xl mb-2">📄</div>
                            <p>还没有上传任何PDF文件</p>
                        </div>
                    `;
                    mergeBtn.disabled = true;
                    downloadBtn.disabled = true;
                    return;
                }
                
                pdfList.innerHTML = '';
                pdfFiles.forEach((file, index) => {
                    const fileSize = (file.size / (1024 * 1024)).toFixed(2);
                    const fileItem = document.createElement('div');
                    fileItem.className = 'pdf-item';
                    fileItem.innerHTML = `
                        <div class="flex-shrink-0 text-2xl mr-4">📄</div>
                        <div class="flex-grow mr-4 overflow-hidden">
                            <h4 class="font-medium text-gray-800 truncate">${file.name}</h4>
                            <p class="text-sm text-gray-500">${fileSize} MB</p>
                        </div>
                        <div class="flex items-center space-x-2">
                            <button class="move-up-btn btn btn-neutral p-2" data-index="${index}">
                                <span>⬆️</span>
                            </button>
                            <button class="move-down-btn btn btn-neutral p-2" data-index="${index}">
                                <span>⬇️</span>
                            </button>
                            <button class="remove-btn btn btn-danger p-2" data-index="${index}">
                                <span>❌</span>
                            </button>
                        </div>
                    `;
                    pdfList.appendChild(fileItem);
                    
                    // 绑定移动和删除按钮事件
                    fileItem.querySelector('.move-up-btn').addEventListener('click', () => moveFile(index, -1));
                    fileItem.querySelector('.move-down-btn').addEventListener('click', () => moveFile(index, 1));
                    fileItem.querySelector('.remove-btn').addEventListener('click', () => removeFile(index));
                });
                
                // 启用合并按钮
                mergeBtn.disabled = pdfFiles.length < 2;
                downloadBtn.disabled = !mergedPdfBytes;
            }
            
            // 移动文件位置
            function moveFile(index, direction) {
                if (direction === -1 && index === 0) return; // 已经在顶部
                if (direction === 1 && index === pdfFiles.length - 1) return; // 已经在底部
                
                const newIndex = index + direction;
                [pdfFiles[index], pdfFiles[newIndex]] = [pdfFiles[newIndex], pdfFiles[index]];
                updateFileList();
            }
            
            // 删除文件
            function removeFile(index) {
                pdfFiles.splice(index, 1);
                updateFileList();
            }
            
            // 显示进度条
            function showProgress() {
                progressContainer.classList.remove('hidden');
                progressBar.style.width = '0%';
                progressText.textContent = '准备中...';
            }
            
            // 隐藏进度条
            function hideProgress() {
                progressContainer.classList.add('hidden');
            }
            
            // 显示结果模态框
            function showResultModal() {
                resultModal.classList.remove('hidden');
            }
            
            // 隐藏结果模态框
            function hideResultModal() {
                resultModal.classList.add('hidden');
            }
            
            // 合并PDF文件
            async function mergePdfs() {
                const { PDFDocument, rgb } = PDFLib;
                const mergedPdf = await PDFDocument.create();
                
                for (let i = 0; i < pdfFiles.length; i++) {
                    const file = pdfFiles[i];
                    const arrayBuffer = await readFileAsArrayBuffer(file);
                    const pdfDoc = await PDFDocument.load(arrayBuffer);
                    
                    // 更新进度
                    const progress = ((i + 1) / pdfFiles.length) * 100;
                    progressBar.style.width = `${progress}%`;
                    progressText.textContent = `正在处理 ${file.name} (${i + 1}/${pdfFiles.length})`;
                    
                    // 复制页面
                    const pages = await mergedPdf.copyPages(pdfDoc, pdfDoc.getPageIndices());
                    pages.forEach(page => {
                        mergedPdf.addPage(page);
                    });
                    
                    // 模拟延迟，使进度条更流畅
                    await new Promise(resolve => setTimeout(resolve, 200));
                }
                
                // 保存合并后的PDF
                mergedPdfBytes = await mergedPdf.save();
                downloadBtn.disabled = false;
            }
            
            // 读取文件为ArrayBuffer
            function readFileAsArrayBuffer(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = () => resolve(reader.result);
                    reader.onerror = reject;
                    reader.readAsArrayBuffer(file);
                });
            }
        });
    </script>
</body>
</html>
    